package com.tsd.common.service.impl;

import com.tsd.common.dao.CommonSnValueMapper;
import com.tsd.common.entity.CommonSnValue;
import com.tsd.common.entity.CommonSnValueExt;
import com.tsd.common.service.CommonSnValueService;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.PageBean;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 描述：CommonSnValue 服务实现层
 *
 * @author huawei
 * @date 2020/07/29 17:08:20
 */
@Service
public class CommonSnValueServiceImpl extends BaseServiceImpl implements CommonSnValueService {

    @Resource
    private CommonSnValueMapper commonSnValueMapper;
    @Resource
    private DataSourceTransactionManager txManager;

    @Override
    public CommonSnValue getCommonSnValueById(Long id) throws Exception {
        return commonSnValueMapper.selectByPrimaryKey(id);
    }

    @Override
    public CommonSnValueExt queryBySid(String sid) throws Exception {
        return commonSnValueMapper.selectBySid(sid);
    }

    @Override
    public void deleteCommonSnValue(Long id, SysUserExt opUser) throws Exception {
        CommonSnValue old = commonSnValueMapper.selectByPrimaryKey(id);
        super.checkEmpty(old, "该记录不存在");
        super.autoInjectBaseData(old, opUser, TYPE_DELETE);
        commonSnValueMapper.updateByPrimaryKeySelective(old);
    }

    @Override
    public void saveCommonSnValue(CommonSnValue record, SysUserExt opUser) throws Exception {
        if (HlpUtils.isEmpty(record.getId())) {
            super.checkEmpty(record.getCode(), "请输入编码");
            super.checkEmpty(record.getName(), "请输入名称");
            super.autoInjectBaseData(record, opUser, TYPE_CREATE);
            commonSnValueMapper.insertSelective(record);
        } else {
            super.autoInjectBaseData(record, opUser, TYPE_UPDATE);
            commonSnValueMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public List<CommonSnValueExt> findCommonSnValues(Map<String, Object> params, PageBean page) throws Exception {
        return commonSnValueMapper.selectByPage(params, page);
    }

    @Override
    public List<CommonSnValueExt> findCommonSnValues(Map<String, Object> params) throws Exception {
        return commonSnValueMapper.selectByParams(params);
    }


    @Override
    synchronized public int genNextValue(String code, Integer num, SysUser opUser, boolean is_save) throws HlpException {
        //2023-09-07 将编号生成改为与业务共一个事务，避免跳号的情况
        //编码采用与业务同一个事务之后，需要注意mybatis的缓存功能，多次查询数据得到的数据是缓存中的数据，优化更新sn表的功能，否则出现无法提交的bug
//		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
//		TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
//		try {
        CommonSnValueExt val = commonSnValueMapper.selectByCode(code);
        if (val == null) {
            val = new CommonSnValueExt();
            val.setCode(code);
            val.setValue(1);
            if (is_save) {
                super.autoInjectBaseData(val, opUser, this.TYPE_CREATE);
                commonSnValueMapper.insert(val);
            }
            return val.getValue();
        } else {
            if (is_save) {
                Integer nextSn = getNextSnValue(val.getValue(), num);
                val.setOldValue(val.getValue());
                val.setValue(nextSn);
                if (nextSn == 1) {
                    val.setOldValue(null);
                }
                super.autoInjectBaseData(val, opUser, this.TYPE_UPDATE);
                int count = commonSnValueMapper.updateByPrimaryKeyAndOldVal(val);
                int tries = 0;
                while (count == 0) {
                    tries++;
                    if (tries > 10) {
                        throw new HlpException("生成编码繁忙，请稍后再试");
                    }
                    nextSn = getNextSnValue(val.getValue(), num);
                    val.setOldValue(val.getValue());
                    val.setValue(nextSn);
                    if (nextSn == 1) {
                        val.setOldValue(null);
                    }
                    super.autoInjectBaseData(val, opUser, this.TYPE_UPDATE);
                    count = commonSnValueMapper.updateByPrimaryKeyAndOldVal(val);
                }
                return val.getValue();
            } else {
                return getNextSnValue(val.getValue(), num);
            }
        }
//			txManager.commit(status);
//		} catch (Exception e) {
//			txManager.rollback(status);
//		}
//		return 0;
    }

    /**
     * 下一个序号
     *
     * @param value
     * @param num
     * @return
     */
    private Integer getNextSnValue(Integer value, int num) {
        // 超过位数初始化1
        Integer tempValue = value + 1;
        if (tempValue.toString().length() > num) {
            tempValue = 1;
        }
        return tempValue;
    }

    @Override
    public CommonSnValueExt getCommonSnValueByCode(String code) throws Exception {
        CommonSnValue params = new CommonSnValue();
        params.setDr(0);
        params.setCode(code);
        List<CommonSnValueExt> list = commonSnValueMapper.selectByEntity(params);
        CommonSnValueExt valueExt;
        if (!HlpUtils.isEmptyList(list)) {
            valueExt = list.get(0);
            valueExt.setValue(valueExt.getValue() + 1);
            return valueExt;
        } else {
            valueExt = new CommonSnValueExt();
            valueExt.setValue(1);
        }
        return valueExt;
    }

}
